package com.bthdung.studios.lesson12.framework;

import android.graphics.Bitmap;
import android.opengl.GLES20;
import android.opengl.GLUtils;

// Handles creating a texture using a bitmap;
public class Texture2D
{
	int id;
	
	public Texture2D(Bitmap bitmap)
	{
		id = glLoadTexture(bitmap);
	}

	public int getId()
	{
		return id;
	}
	
	public void glActivate(int textureSlot)
	{
		GLES20.glActiveTexture(textureSlot);
		GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, id);
	}
	
	static int glLoadTexture(Bitmap bitmap)
	{
		final int[] textureHandle = new int[1];
		GLES20.glGenTextures(1, textureHandle, 0);

		if (textureHandle[0] != 0)
		{
			// Bind to the texture in OpenGL
			GLES20.glBindTexture(GLES20.GL_TEXTURE_2D, textureHandle[0]);

			// Set filtering
			GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MIN_FILTER, GLES20.GL_NEAREST);
			GLES20.glTexParameteri(GLES20.GL_TEXTURE_2D, GLES20.GL_TEXTURE_MAG_FILTER, GLES20.GL_NEAREST);

			// Load the bitmap into the bound texture.
			GLUtils.texImage2D(GLES20.GL_TEXTURE_2D, 0, bitmap, 0);

			// Recycle the bitmap, since its data has been loaded into OpenGL.
			bitmap.recycle();
		}

		if (textureHandle[0] == 0) { throw new RuntimeException("Error loading texture."); }

		return textureHandle[0];
	}
}

